﻿using log4net;
using Microsoft.Owin.Hosting;
using System;
using System.Configuration;
using Topshelf;


[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace aier.wx.api.selfhost
{
	class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>                                        //1
            {
                x.Service<ApiServiceSelfHost>(s =>                         //2
                {
                    s.ConstructUsing(name => new ApiServiceSelfHost());    //3
                    s.WhenStarted(tc => tc.Start());                    //4
                    s.WhenStopped(tc => tc.Stop());                     //5
                });
                x.RunAsLocalSystem();                                    //6

                x.SetDescription("Aier APIService Topshelf Host");       //7
                x.SetDisplayName("Aier APIService");                 //8
                x.SetServiceName("Aier APIService");                 //9
            });

            Console.ReadKey();
        }
    }

    public class ApiServiceSelfHost
    {
        private readonly string baseUrl = string.Empty;
        IDisposable startUp = null;
        ILog log = null;

        public ApiServiceSelfHost()
        {
            baseUrl = ConfigurationManager.AppSettings["ApiServiceUrl"];
            log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }

        public void Start()
        {
            startUp = WebApp.Start<Startup>(baseUrl);
            log.Info("AIER API Service Start Success");
        }

        public void Stop()
        {
            if (startUp != null)
            {
                startUp.Dispose();
                log.Info("AIER API Service Shutdown Success");
            }
        }
    }
}
